package com.lvmama.rhino.common.utils.methodset

import com.lvmama.rhino.common.utils.logging.LazyLogging

import scala.util.Try
import scala.util.parsing.json.JSON
import scalaj.http.{HttpOptions, HttpRequest}

/**
  * Created by yuanxiaofeng on 2017/5/23.
  */
object InterfaceInvoke extends Serializable with LazyLogging{

  def getUserCreatedDate(userId: String): String = {
    val result = httpGet()
      .param("userNo", userId)
      .asString

    val createdDate = JSON.parseFull(result.body).get.asInstanceOf[Map[String, AnyRef]].getOrElse("data", Map.empty[String, String])
      .asInstanceOf[Map[String, String]].getOrElse("createdDate", "")

    logger.debug(s"InterfaceInvoke getUserCreatedDate $userId's create date is $createdDate")

    createdDate
  }

  def httpGet(): HttpRequest = {
    scalaj.http.Http("http://m.lvmama.com/usso/router/rest.do?method=api.com.user.getUser&version=1.0.0")
      .header("signal", "ab4494b2-f532-4f99-b57e-7ca121a137ca")
      .header("Charset", "UTF-8")
      .option(HttpOptions.readTimeout(10000))
  }

  def getDeviceChannel(deviceToken: String, deviceType: String, secondChannel: String): String = {
    val url = s"http://m.lvmama.com/zhuanti/api/activity/getPhoneInfo?muid=$deviceToken&type=$deviceType"
    val result = Try(scalaj.http.Http(url)
      .option(HttpOptions.readTimeout(5000))
      .asString
      .body)

    val sc =
      try {
        if (result.isSuccess && !result.get.startsWith("非法访问")) {
          val map = JSON.parseFull(result.get).get.asInstanceOf[Map[String, AnyRef]]
          if (map.get("code").get.toString == "1.0") {
            val datas = map.get("datas").get.asInstanceOf[Map[String, List[Map[String, String]]]].get("list").get
            if (datas.isEmpty) {
              secondChannel
            } else {
              datas.head.getOrElse("channel", secondChannel)
            }
          } else {
            secondChannel
          }
        } else {
          secondChannel
        }
      } catch {
        case e: Exception => secondChannel
      }

    logger.debug(s"InterfaceInvoke getDeviceChannel $url")

    sc
  }

}
